package com.tju.resource.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tju.resource.common.ServiceException;
import com.tju.resource.mapper.*;
import com.tju.resource.model.*;
import com.tju.resource.server.TbOutwardService;
import com.tju.resource.tool.result.Result;
import com.tju.resource.tool.result.ResultEnum;
import com.tju.resource.tool.result.ResultUtil;
import com.tju.resource.tool.tool.EmptyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Date;
import java.util.Map;

@Service
public class TbOutwardServiceImpl implements TbOutwardService {

    @Autowired
    TbOutwardMapper mapper;
    /*外发，物料，订单中间表*/
    @Autowired
    TbOutwardOrderMapper tbOutwardOrderMapper;
    /*外发，耗材，中间表*/
    @Autowired
    TbOutwardConsumablesMapper tbOutwardConsumablesMapper;
    @Autowired
    TbMaterialMapper tbMaterialMapper;
    @Autowired
    TbConsumablesMapper tbConsumablesMapper;

    /**
     * 查询外发信息
     *
     * @param params
     * @return
     */
    @Override
    public Result<Object> getAll(@RequestBody Map<String, String> params) {
        try {
            Page<TbOutward> page = new Page<>(Long.parseLong(params.get("page")), Long.parseLong(params.get("limit")));
            IPage<TbOutward> iPage = mapper.getAll(page, params);
            return ResultUtil.success(ResultEnum.SUCCESS, iPage.getRecords(), iPage.getTotal());
        } catch (Exception e) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, e.getMessage());
        }
    }

    /**
     * 添加外发信息
     *
     * @param outward
     * @return
     */
    @Override
    @Transactional
    public Result<Object> add(TbOutward outward) {
        int totalNumber = 0;
        double totalAmount = 0;
        if (mapper.insert(outward) > 0) {
            for (TbOutwardOrder outwardOrder : outward.getOutwardOrderList()) {
                if (EmptyUtils.isEmpty(outwardOrder.getId()) && EmptyUtils.isEmpty(outwardOrder.getMechanicalId())) {
                    throw new ServiceException("请选择订单和物料！");
                }
                if (outwardOrder.getOutwardNumber() > outwardOrder.getSpPcs()) {
                    throw new ServiceException("外发数量不能大于半成品数量！");
                }
                outwardOrder.setOrderId(outwardOrder.getId());
                outwardOrder.setId(null);
                totalNumber += outwardOrder.getOutwardNumber();
                totalAmount += outwardOrder.getAmount();
                outwardOrder.setOutwardId(outward.getId());
                tbOutwardOrderMapper.insert(outwardOrder);
            }
            UpdateWrapper<TbOutward> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", outward.getId());
            wrapper.set("total_number", totalNumber);
            wrapper.set("total_amount", totalAmount);
            mapper.update(null, wrapper);
        }
        return ResultUtil.success(ResultEnum.SUCCESS);
    }


    /**
     * 修改外发信息
     *
     * @param outward
     * @return
     */
    @Override
    @Transactional
    public Result<Object> upd(TbOutward outward) {
        try {
            int totalNumber = 0;
            double totalAmount = 0;
            if (mapper.updateById(outward) > 0) {
                tbOutwardOrderMapper.delete(new QueryWrapper<TbOutwardOrder>().eq("outward_id", outward.getId()));
                for (TbOutwardOrder outwardOrder : outward.getOutwardOrderList()) {
                    if (EmptyUtils.isEmpty(outwardOrder.getId()) && EmptyUtils.isEmpty(outwardOrder.getMechanicalId())) {
                        throw new ServiceException("请选择订单和物料！");
                    }
                    if (outwardOrder.getOutwardNumber() > outwardOrder.getSpPcs()) {
                        throw new ServiceException("外发数量不能大于半成品数量！");
                    }
                    outwardOrder.setOrderId(outwardOrder.getId());
                    outwardOrder.setId(null);
                    totalNumber += outwardOrder.getOutwardNumber();
                    totalAmount += outwardOrder.getAmount();
                    outwardOrder.setOutwardId(outward.getId());
                    tbOutwardOrderMapper.insert(outwardOrder);
                }
                UpdateWrapper<TbOutward> wrapper = new UpdateWrapper<>();
                wrapper.eq("id", outward.getId());
                wrapper.set("total_number", totalNumber);
                wrapper.set("total_amount", totalAmount);
                mapper.update(null, wrapper);
                return ResultUtil.success(ResultEnum.SUCCESS);
            }
        } catch (Exception e) {
            throw new ServiceException("修改失败！");
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR);
    }

    /**
     * 删除
     *
     * @param oId
     * @return
     */
    @Override
    @Transactional
    public Result<Object> del(Long oId) {
        try {
            if (mapper.deleteById(oId) > 0) {
                tbOutwardOrderMapper.delete(new QueryWrapper<TbOutwardOrder>().eq("outward_id", oId));
                return ResultUtil.success(ResultEnum.SUCCESS);
            } else
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, "删除失败！");
        } catch (Exception e) {
            throw new ServiceException("修改失败！");
        }
    }

    /**
     * 审核
     *
     * @return
     */
    @Override
    @Transactional
    public Result<Object> check(TbOutward tbOutward) {
        UpdateWrapper<TbOutward> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", tbOutward.getId());
        wrapper.set("reviewer", tbOutward.getReviewer());
        wrapper.set("audit_time", new Date());
        wrapper.set("approve_state", 1);
        if (mapper.update(null, wrapper) > 0) {
            UpdateWrapper<TbOutwardOrder> updateWrapper = new UpdateWrapper<>();
            for (TbOutwardOrder order : tbOutward.getOutwardOrderList()) {
                if (order.getQualified() > 0 && EmptyUtils.isNotEmpty(order.getId())) {
                    if (order.getQualified() > order.getOutwardNumber()) {
                        throw new ServiceException("合格数不能大于外发数!");
                    }
                    updateWrapper.eq("id", order.getOrderId());
                    updateWrapper.set("qualified", order.getQualified());
                    updateWrapper.set("qualified_state", ((order.getOutwardNumber() * order.getScrapRate()) >= order.getQualified()) ? 1 : 0);
                    if (tbOutwardOrderMapper.update(null, updateWrapper) == 0) {
                        throw new ServiceException("审核失败!");
                    }
                    UpdateWrapper<TbMaterial> wrapper1 = new UpdateWrapper<>();
                    wrapper1.eq("id", order.getMechanicalId());
                    wrapper1.set("fp_pcs", order.getFpPcs() + order.getOutwardNumber());
                    tbMaterialMapper.update(null, wrapper1);
                } else {
                    throw new ServiceException("请输入合格数量!");
                }
            }
            return ResultUtil.success(ResultEnum.SUCCESS, "审核成功！");
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, "审核失败！");
    }

    /**
     * 判断供应商需要删除是否外发已使用
     *
     * @param supplierId
     * @return
     */
    @Override
    public Boolean judgmentSupplier(Long supplierId) {
        try {
            QueryWrapper<TbOutward> wrapper = new QueryWrapper<>();
            wrapper.eq("supplier_id", supplierId);
            if (EmptyUtils.isNotEmpty(mapper.selectList(wrapper)))
                return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 外发单添加,修改耗材物品
     *
     * @return
     */
    @Transactional
    @Override
    public Result<Object> managementConsumables(TbOutwardConsumables tbOutwardConsumables) {
        QueryWrapper<TbOutwardConsumables> wrapper = new QueryWrapper<>();
        wrapper.eq("outward_id", tbOutwardConsumables.getOutwardId());
        tbOutwardConsumablesMapper.delete(wrapper);
        if (EmptyUtils.isNotEmpty(tbOutwardConsumables.getConsumablesList()))
            for (TbConsumables consumable : tbOutwardConsumables.getConsumablesList()) {
                System.err.println(consumable);
                if (EmptyUtils.isEmpty(consumable.getUsageAmount()))
                    throw new ServiceException("请输入使用数量！");
                if (consumable.getNumber() < consumable.getUsageAmount())
                    throw new ServiceException("使用数量不能大于仓库总数量！");
                if (tbOutwardConsumablesMapper.insert(new TbOutwardConsumables(tbOutwardConsumables.getOutwardId(), consumable.getId(), consumable.getUsageAmount())) == 0)
                    throw new ServiceException("执行失败！");
            }
        return ResultUtil.success(ResultEnum.SUCCESS, "执行成功！");
    }

    /**
     * 一次审核
     *
     * @param outward
     * @return
     */
    @Transactional
    @Override
    public Result<Object> oneAudit(TbOutward outward) {
        if (EmptyUtils.isNotEmpty(outward.getOutwardOrderList()))
            for (TbOutwardOrder order : outward.getOutwardOrderList()) {
                UpdateWrapper<TbMaterial> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", order.getMechanicalId());
                updateWrapper.set("sp_pcs", order.getSpPcs() - order.getOutwardNumber());
                if (tbMaterialMapper.update(null, updateWrapper) == 0)
                    throw new ServiceException("审核失败！");
            }
        if (EmptyUtils.isNotEmpty(outward.getTbOutwardConsumablesList()))
            for (TbOutwardConsumables consumables : outward.getTbOutwardConsumablesList()) {
                UpdateWrapper<TbConsumables> wrapper = new UpdateWrapper<>();
                wrapper.eq("id", consumables.getTbConsumables().getId());
                wrapper.set("number", consumables.getTbConsumables().getNumber() - consumables.getUsageAmount());
                if (tbConsumablesMapper.update(null, wrapper) == 0)
                    throw new ServiceException("审核失败！");
            }
        return ResultUtil.success(ResultEnum.SUCCESS, "审核成功！");
    }

}
